package com.ch.engine.biz.likou;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 一些算法题
 *
 * @author wangchunhui
 * @date 2024/10/31 17:10
 */
public class Solution {

    /**
     * 寻找数组的中心索引
     *
     * @return int
     * @author wangchunhui
     * @date 2024/10/31 17:34
     */
    public static int pivotIndex(int[] nums) {
        int total = Arrays.stream(nums).sum();
        int sum = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (2 * sum + nums[i] == total) {
                return i;
            }
            sum += nums[i];
        }
        return -1;
    }

    /**
     * 搜索插入位置
     *
     * @return int
     * @author wangchunhui
     * @date 2024/10/31 17:49
     */
    public static int searchInsert(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= target) {
                return i;
            }
        }
        return nums.length;
    }

    /**
     * 合并区间
     *
     * @return int[][]
     * @author wangchunhui
     * @date 2024/11/1 15:47
     */
    public static int[][] merge(int[][] intervals) {
        List<int[]> list = new ArrayList<>();
        for (int[] interval : intervals) {
            int i = interval[0];
            int j = interval[1];
            for (int[] interval1 : intervals) {
                int m = interval1[0];
                int n = interval1[1];
                if (i <= m && j >= m && j <= n) {
                    int[] interval2 = {i, n};
                    list.add(interval2);
                }
            }
        }
        list = list.stream().distinct().collect(Collectors.toList());
        int[][] array = new int[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }


    public static void main(String[] args) {
//        int[] nums = {1, 7, 3, 6, 5, 6};
//        System.out.println(pivotIndex(nums));

//        int[] nums = {1, 3, 5, 6};
//        int target = 5;
//        System.out.println(searchInsert(nums, target));

        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        System.out.println(Arrays.deepToString(merge(intervals)));
    }
}